package org.adream.account.rest.frontApi;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Date;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.adream.account.entity.AccountCancelEntity;
import org.adream.account.entity.CmsLogEntity;
import org.adream.account.entity.LoginPageFilesEntity;
import org.adream.account.entity.OAuthMemoryEntity;
import org.adream.account.entity.UserEntity;
import org.adream.account.model.ResultModel;
import org.adream.account.rest.api.model.FrontBasicInfoForm;
import org.adream.account.rest.api.model.LoginForm;
import org.adream.account.rest.api.model.RegForm;
import org.adream.account.rest.api.model.UserForm;
import org.adream.account.service.ADreamServiceException;
import org.adream.account.service.CmsLogService;
import org.adream.account.service.HrmResourceService;
import org.adream.account.service.LoginPageFilesService;
import org.adream.account.service.MemoryTokenService;
import org.adream.account.service.UserService;
import org.adream.account.service.ValidateService;
import org.adream.account.util.Constant;
import org.adream.account.util.FastJson;
import org.adream.account.util.UserUtil;
import org.adream.account.util.Utils;
import org.adream.account.util.ZXingUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPObject;
import com.sensorsdata.analytics.javasdk.exceptions.InvalidArgumentException;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;

/**
 * 前端user
 * 
 * @author sl
 *
 */
@RequestMapping("/userFront/")
@Controller
public class UserFrontApiController {

	private final static Logger logger = LoggerFactory.getLogger(UserFrontApiController.class);

	@Autowired
	private UserService userService;

	@Autowired
	private ValidateService validateService;

	@Autowired
	private MemoryTokenService memoryTokenService;
	
	@Autowired
	private HrmResourceService hrmResourceService;
	
	@Autowired
	private CmsLogService cmsLogService;
	
	@Autowired
	private LoginPageFilesService loginPageFilesService;
	/**
	 * 发送邮箱验证码
	 * 
	 * @param email
	 * @param code
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "sendCodeEmailValidate", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	@ResponseBody
	public ResultModel<?> sendEmail(@FastJson("email") String email,
			@FastJson(value = "flag", required = false) Integer flag, HttpServletRequest request) {
		// 检查邮箱
		boolean isExistEmail = userService.isExistEmail(email.toLowerCase().trim());
		// flag为1时,适用于忘记密码
		if (Constant.ONE == flag) {
			if (!isExistEmail) {
				return new ResultModel<String>(ResultModel.ERR_PARAM, "邮箱未注册", null);
			}
		} else if (Constant.TWO == flag) {
			// flag为2时,适用于新增绑定
			if (isExistEmail) {
				return new ResultModel<String>(ResultModel.ERR_PARAM, "邮箱已注册", null);
			}
		}

		validateService.sendIdentifyCodeByEmail(email, request);

		if (Constant.ONE == flag) {
			HttpSession session = request.getSession();
			//邮箱@后面全部置为小写
			String prefixEmail = email.substring(0, email.lastIndexOf("@"));
			String suffixEmail = email.substring(email.lastIndexOf("@"));
			session.setAttribute("login", prefixEmail + suffixEmail.toLowerCase());
//				session.setAttribute("login", email);
		}

		return new ResultModel<String>(ResultModel.SUCCESS, "发送成功", null);
	}

	/**
	 * 发送手机验证码
	 * 
	 * @param phone
	 *            手机号码
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "sendCodeSmsValidate", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	@ResponseBody
	public ResultModel<?> sendCodeSmsValidate(@FastJson("phone") String phone,
			@FastJson(value = "flag", required = false) Integer flag,String checkCode, HttpServletRequest request) {
		if(StringUtils.isEmpty(checkCode)){
			return new ResultModel<String>(ResultModel.ERR_PARAM, ResultModel.ERR_PARAM_MSG, "我们做公益，不盈利，我们资金有限，请不要攻击我们。");
		}
		boolean isExistPhone = false;
		// 检查手机号 当 flag=6 时 没有手机号参数
		if ( Constant.SIX != flag ) {
			isExistPhone = userService.isExistPhone(phone);
		}
		
		if (Constant.TWO == flag) {
			// flag为2时,适用于新增绑定
			if (isExistPhone) {
				return new ResultModel<String>(ResultModel.ERR_PARAM, "手机号已存在", null);
			}
		} else if (Constant.ONE == flag) {
			// flag 默认存在于系统，才发送验证码。
			if (!isExistPhone) {
				return new ResultModel<String>(ResultModel.ERR_PARAM, "手机号未注册", null);
			}
		} else if(Constant.FIVE == flag) {
			// flag为5时,注销账号
			if(!isExistPhone) {
				return new ResultModel<String>(ResultModel.NOT_FOUND_OBJECT, "手机号未注册", null);
			}
		} else if(Constant.NINE == flag) {
			// flag为9时,合并账户绑定  sendCode 存 session 不一样 合并账户时不管哪种登录成功清除这些session
			if (!isExistPhone) {
				return new ResultModel<String>(ResultModel.ERR_PARAM, "手机号未注册", null);
			}
		} else if(Constant.SIX == flag) {
			// flag为6时,二次登陆
			String uid = UserUtil.getUidByRequest(request);
			if(StringUtils.isEmpty(uid)) {
				return new ResultModel<String>(ResultModel.ERR_PARAM, "获取失败,uid参数为空", null);
			}else{
				UserEntity userEntity = userService.queryUserByUid(uid);
				if(userEntity != null) {
					phone = userEntity.getPhone();
				}else {
					return new ResultModel<String>(ResultModel.ERR_PARAM, "获取失败,未找到对应用户信息", null);
				}
				 
			}
			//此处就写在了 6 的分支  其他逻辑不清楚
			if(StringUtils.isEmpty(phone) || phone.length() != 11) {
				return new ResultModel<String>(ResultModel.ERR_PARAM, "获取失败,手机号根式不正确或为空！", null);
			}
		}
		
		validateService.sendIdentifyCodeByPhone(phone, request,flag ,checkCode);

		if (Constant.ONE == flag) {
			HttpSession session = request.getSession();
			session.setAttribute("login", phone);
		}
		 
		return new ResultModel<String>(ResultModel.SUCCESS, "发送成功", null);
	}

	/**
	 * 检查手机是否已经注册
	 * 
	 * @param phone
	 *            手机号码
	 * @return
	 */
	@RequestMapping(value = "checkPhone", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public ResultModel<?> checkPhone(String phone) {
		boolean isExistPhone = userService.isExistPhone(phone);
		return new ResultModel<String>(ResultModel.SUCCESS, "成功", String.valueOf(isExistPhone));
	}

	/**
	 * 检查邮箱是否已绑定
	 * 
	 * @param email
	 *            邮箱
	 * @return
	 */
	@RequestMapping(value = "checkEmail", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public ResultModel<?> checkEmail(String email) {
		boolean isExistEmail = userService.isExistEmail(email);
		return new ResultModel<String>(ResultModel.SUCCESS, "成功", String.valueOf(isExistEmail));
	}
	
	/**
	 * 注册
	 * @param form   注册表单
	 * @param request  
	 * @return
	 */
	@RequestMapping(value = "reg/{refererUrl}", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public ResultModel<?> reg(@PathVariable String refererUrl,@RequestBody RegForm form, HttpServletRequest request) {
		try {
			return userService.reg(refererUrl,form, request);
		} catch (IOException e) {
			logger.warn("注册失败," + e.getMessage());
			return new ResultModel<String>(ResultModel.ERR_SYS, "系统错误0107,请联系管理员", null);
		} catch (InvalidArgumentException e) {
			logger.warn("注册失败," + e.getMessage());
			return new ResultModel<String>(ResultModel.ERR_SYS, "系统错误0107-2,请联系管理员", null);
		}
	}

	/**
	 * 短信登录
	 * 
	 * @param phone
	 * @return
	 */
	@RequestMapping(value = "loginbymsg", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public ResultModel<?> loginByMessage(HttpServletRequest request, @RequestBody LoginForm form) {
		logger.debug("通过短信登录");
		if(form == null || StringUtils.isEmpty(form.getLogin()) || StringUtils.isEmpty(form.getCheckCode())) {
			logger.warn("短信登录失败,请求参数为空:(");
			return new ResultModel<String>(ResultModel.ERR_PARAM, "请求参数有误", null);
		}
		if(!Utils.verifyPhone(form.getLogin())) {
			logger.warn("短信登录失败,手机号码格式有误:(");
			return new ResultModel<String>(ResultModel.ERR_PARAM, "手机号码格式有误", null);
		}
		boolean b = validateService.verifyPhoneIdentifyCode(form.getCheckCode(), request);
		if (b) {
			if (StringUtils.isEmpty(form.getLogin())) {
				return new ResultModel<String>(ResultModel.ERR_PARAM, "手机号为空", null);
			}
			UserEntity user = userService.queryUserByPhone(form.getLogin());
			memoryTokenService.replaceIntoOAuthMemory(user.getUid(), form.getLogin(), form.getCheckCode(),
					Constant.MESSAGE_TOKEN_ALIVE); // token生存3分钟
			return new ResultModel<OAuthMemoryEntity>(ResultModel.SUCCESS, ResultModel.SUCCESS_MSG, null);
		} else {
			// 验证失败
			return new ResultModel<String>(ResultModel.ERR_PARAM, "验证码错误", null);
		}
	}

	/**
	 * 检查用户名是否存在
	 * 
	 * @param uname
	 *            用户名
	 * @return
	 */
	@RequestMapping(value = "checkUname", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public ResultModel<?> checkUname(String uname) {
		boolean isExistUname = userService.isExistUname(uname,null);
		return new ResultModel<String>(ResultModel.SUCCESS, "成功", String.valueOf(isExistUname));
	}

	/**
	 * 更新手机号码
	 * 
	 * @param form
	 *            用户表单
	 * @return
	 */
	@RequestMapping(value = "updateUserPhone", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public ResultModel<?> updateUserPhone(@RequestBody UserForm form, HttpServletRequest request) {
		if (form == null || StringUtils.isEmpty(form.getCode()) || StringUtils.isEmpty(form.getPhone())) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "更新失败,请求参数有误", null);
		}
		if(!Utils.verifyPhone(form.getPhone())) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "更新失败,手机号码格式有误", null);
		}
		String uid = UserUtil.getUidByRequest(request);
		if(StringUtils.isEmpty(uid)) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "更新失败,登录信息失效,请重新登录", null);
		}
		form.setUid(uid);
		if (!validateService.verifyPhoneIdentifyCode(form.getCode(), request)) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "验证码输入有误", null);
		}
		return userService.updateUserPhone(form);
	}

	/**
	 * 更新邮箱
	 * 
	 * @param form
	 *            用户表单
	 * @return
	 */
	@RequestMapping(value = "updateUserEmail", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public ResultModel<?> updateUserEmail(@RequestBody UserForm form, HttpServletRequest request) {
		if (form == null || StringUtils.isEmpty(form.getCode()) || StringUtils.isEmpty(form.getEmail())) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "更新失败,请求参数有误", null);
		}
		if(!Utils.verifyEmail(form.getEmail())) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "更新失败,邮箱格式有误", null);
		}
		String uid = UserUtil.getUidByRequest(request);
		if(StringUtils.isEmpty(uid)) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "更新失败,登录信息失效,请重新登录", null);
		}
		form.setUid(uid);
		if (!validateService.verifyEmailIdentifyCode(form.getCode(), request)) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "验证码输入有误", null);
		}
		return userService.updateUserEmail(form);
	}

	/**
	 * 验证手机验证码
	 * 
	 * @param code
	 *            手机验证码
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "verifyPhoneCode", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	@ResponseBody
	public ResultModel<?> verifyPhoneCode(String code, HttpServletRequest request) {
		if (StringUtils.isEmpty(code)) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "验证错误,请求参数有误", null);
		}
		boolean isRightCode = validateService.verifyPhoneIdentifyCode(code, request);
		return new ResultModel<Boolean>(ResultModel.SUCCESS, "成功验证", isRightCode);
	}

	/**
	 * 验证邮箱验证码
	 * 
	 * @param code
	 *            邮箱验证码
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "verifyEmailCode", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	@ResponseBody
	public ResultModel<?> verifyEmailCode(String code, HttpServletRequest request) {
		if (StringUtils.isEmpty(code)) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "验证错误,请求参数有误", null);
		}
		boolean isRightCode = validateService.verifyEmailIdentifyCode(code, request);
		return new ResultModel<Boolean>(ResultModel.SUCCESS, "成功验证", isRightCode);
	}

	/**
	 * 二维码生成
	 * @param info
	 * @param width
	 * @param height
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "createQrCode")
	public void createQrCode(@RequestParam(value = "info") String info,
			@RequestParam(value = "width", required = false) Integer width,
			@RequestParam(value = "height", required = false) Integer height, HttpServletRequest request,
			HttpServletResponse response) {
		if (StringUtils.isEmpty(info)) {
			logger.info("请求参数有误:)");
			return;
		}
		response.setDateHeader("Expires", 0);
		response.setHeader("Cache-Control", "no-store, no-cache,must-revalidate");
		response.addHeader("Cache-Control", "post-check=0, pre-check=0");
		response.setHeader("Pragma", "no-cache");
		response.setContentType("image/jpeg");

		BufferedImage bi = ZXingUtil.getQRCode(info, width, height);
		try (ServletOutputStream out = response.getOutputStream()) {
			ImageIO.write(bi, "jpg", out);
			out.flush();
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("二位码生成出错:)");
		}
	}

	/**
	 * 更新用户基本资料
	 * 
	 * @param form
	 *            基本资料form表单
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "updateBasicInfo", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public ResultModel<?> updateBasicInfo(@RequestBody FrontBasicInfoForm form, HttpServletRequest request) {
		String uid = UserUtil.getUidByRequest(request);
		if (StringUtils.isEmpty(uid)) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "登录信息异常,请重新登录", null);
		}
		if (form == null) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "保存失败,请求参数为空", null);
		}
		if(StringUtils.isEmpty(form.getUname())) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "保存失败,用户昵称不能为空", null);
		}
		
		try {
			String resp = Utils.instance.verifyContent(form.getUname());
			
			CmsLogEntity cmsLogEntity = new CmsLogEntity();
			cmsLogEntity.setUid(uid);
			cmsLogEntity.setAction(CmsLogEntity.TEXT_ACTION);
			cmsLogEntity.setContent(form.getUname());
			cmsLogEntity.setResponse(resp);
			
			cmsLogService.addEntity(cmsLogEntity);
			
			JSONObject jsonObject = JSONObject.parseObject(resp);
			int retcode = jsonObject.getIntValue("retcode");
			if (retcode != 0) {
				logger.error("安全检测api返回错误，错误码：" + retcode + ",错误消息：" + jsonObject.getString("retmsg"));
			} else {
				Boolean evilFlag = jsonObject.getJSONObject("Response").getJSONObject("Data").getBoolean("EvilFlag");
				if (evilFlag) {
					return new ResultModel<String>(ResultModel.ERR_USER_INFO, "昵称不符合规范!", resp);
				}
			}
		} catch (ADreamServiceException | TencentCloudSDKException e) {
			logger.error(e.getMessage());
		}
		form.setUid(uid);
		try {
			return userService.updateBasicInfo(form);
		} catch (Exception e) {
			logger.warn("用户基本信息更新失败:" + e.getMessage());
			return new ResultModel<String>(ResultModel.ERR_SYS, "系统错误,请联系管理员", null);
		}
	}

	/**
	 * 微信浏览器  手机注册并登录
	 * @param form
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "createUserByPhone/{refererUrl}", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public ResultModel<?> createUserByPhone(@PathVariable String refererUrl,@RequestBody RegForm form, HttpServletRequest request) {
		logger.debug("手机注册并登录");
		try {
			ResultModel<?> rlt = userService.regAndLogin(refererUrl,form, request);
			//acc_oauth_memory表引擎为memory,不支持事务,放入事务中将报错
			if(ResultModel.SUCCESS.equals(rlt.getReturnCode()) && rlt.getReturnObject() != null) {
				//acc_oauth_memory新增或更新记录
				memoryTokenService.replaceIntoOAuthMemory(rlt.getReturnObject().toString(), form.getPhone(), form.getCode(),
						Constant.MESSAGE_TOKEN_ALIVE); // token生存3分钟
				rlt.setReturnObject(null);
			}
			return rlt;
		} catch (IOException e) {
			logger.warn("注册失败," + e.getMessage());
			return new ResultModel<String>(ResultModel.ERR_SYS, "系统错误0107,请联系管理员", null);
		} catch (InvalidArgumentException e) {
			logger.warn("注册失败," + e.getMessage());
			return new ResultModel<String>(ResultModel.ERR_SYS, "系统错误0107-2,请联系管理员", null);
		}
	}
	
	/**
	 * 合并账户 短信登录
	 * 
	 * @param phone
	 * @return 用户信息
	 */
	@RequestMapping(value = "accountMerge/loginbymsg", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public ResultModel<?> accountMergeLoginbymsg(HttpServletRequest request, @RequestBody LoginForm form) {
		logger.debug("通过短信登录");
		if(form == null || StringUtils.isEmpty(form.getLogin()) || StringUtils.isEmpty(form.getCheckCode())) {
			logger.warn("短信登录失败,请求参数为空:(");
			return new ResultModel<String>(ResultModel.ERR_PARAM, "请求参数有误", null);
		}
		if(!Utils.verifyPhone(form.getLogin())) {
			logger.warn("短信登录失败,手机号码格式有误:(");
			return new ResultModel<String>(ResultModel.ERR_PARAM, "手机号码格式有误", null);
		}
		return validateService.verifyPhoneCodeOfMerge(form.getLogin(),form.getCheckCode(), request);
	}
	/**
	 *合并账户时 ，检查手机是否已经注册 ，跟当前登录是否相同
	 * 
	 * @param phone
	 *            手机号码
	 * @return
	 */
	@RequestMapping(value = "accountMerge/checkPhone", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public ResultModel<?> checkPhoneOfMerge(String phone,HttpServletRequest request) {
		if(StringUtils.isEmpty(phone)||StringUtils.isEmpty(phone.trim())) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "程序出错了,请刷新重试", null);
		}
		boolean isExistPhone = userService.isExistPhone(phone);
		if(isExistPhone) {
			UserEntity userEntity = userService.queryUserByUid(UserUtil.getUidByRequest(request));
			if(userEntity==null) {
				return new ResultModel<String>(ResultModel.ERR_PARAM, "当前登录信息有误，请重新登录", null);
			}
			if(!StringUtils.isEmpty(userEntity.getPhone())
					&& !StringUtils.isEmpty(userEntity.getPhone().trim())
					&& userEntity.getPhone().equals(phone)) {
				return new ResultModel<String>(ResultModel.ERR_PARAM, "不能重复登录当前用户", null);
			}
			return new ResultModel<String>(ResultModel.SUCCESS, "可以登录", null);
		} else {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "手机号不存在", null);
		}
	}
	
	/**
	 * 合并账户 用户名密码登录
	 * 
	 * @param phone
	 * @return 用户信息
	 */
	@RequestMapping(value = "accountMerge/login", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public ResultModel<?> accountMergeLogin(@RequestBody JSONObject jsonString,HttpServletRequest request) {
		logger.debug("用户名密码登录");
		String code = jsonString.getString("code");
		String un = jsonString.getString("un");
		String pd = jsonString.getString("pd");
		Object sessionCode = request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
		if(StringUtils.isEmpty(un)||StringUtils.isEmpty(un.trim())) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "用户名参数错误",null);
		}
		if(StringUtils.isEmpty(pd)||StringUtils.isEmpty(pd.trim())) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "密码参数错误",null);
		}
		
		if(StringUtils.isEmpty(code)||StringUtils.isEmpty(code.trim())||sessionCode == null) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "验证码参数错误",null);
		}
		if( !code.trim().toLowerCase().equals(String.valueOf(sessionCode).trim().toLowerCase())){
			return new ResultModel<String>(ResultModel.ERR_PARAM, "验证码填写错误",null);
		}
		return validateService.verifyUnAndPd(un.trim(),pd.trim(), request);
	}
	
	/**
	 * 账号注销短信登录
	 * @param form
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "accountCancel/loginbymsg", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public ResultModel<?> accountCancelLoginByMsg(@RequestBody LoginForm form, HttpServletRequest request) {
		if(form == null || StringUtils.isEmpty(form.getLogin()) || StringUtils.isEmpty(form.getCheckCode())) {
			logger.warn("短信登录失败,请求参数为空:(");
			return new ResultModel<String>(ResultModel.ERR_PARAM, "请求参数有误", null);
		}
		if(!Utils.verifyPhone(form.getLogin())) {
			logger.warn("短信登录失败,手机格式有误:(");
			return new ResultModel<String>(ResultModel.ERR_PARAM, "手机号码格式有误", null);
		}
		return validateService.verifyPhoneCodeOfCancel(form.getLogin(),form.getCheckCode(), request);
	}
	
	/**
	 * 注销账户 用户名密码登录
	 * @param jsonString 用户信息
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "accountCancel/login", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public ResultModel<?> accountCancelLogin(@RequestBody JSONObject jsonString,HttpServletRequest request) {
		logger.debug("用户名密码登录");
		String code = jsonString.getString("code");
		String un = jsonString.getString("un");
		String pd = jsonString.getString("pd");
		Object sessionCode = request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
		if(StringUtils.isEmpty(un) || StringUtils.isEmpty(un.trim())) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "用户名参数错误",null);
		}
		if(StringUtils.isEmpty(pd) || StringUtils.isEmpty(pd.trim())) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "密码参数错误",null);
		}
		
		if(StringUtils.isEmpty(code) || StringUtils.isEmpty(code.trim()) || sessionCode == null) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "验证码参数错误",null);
		}
		if(!code.trim().toLowerCase().equals(String.valueOf(sessionCode).trim().toLowerCase())){
			return new ResultModel<String>(ResultModel.ERR_PARAM, "验证码填写错误",null);
		}
		return validateService.verifyUnAndPdOfCancel(un.trim(),pd.trim(), request);
	}
	
	/**
	 * 账户注销申请
	 * @param accountCancel
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/cancelApplication",produces = "application/json;charset=UTF-8")
	@ResponseBody
	public ResultModel<?> cancelApplication(@RequestBody AccountCancelEntity accountCancel,HttpServletRequest request) {
		if(accountCancel == null || StringUtils.isEmpty(accountCancel.getCancelUid())) {
			logger.warn("注销申请失败,参数为空:(");
			return new ResultModel<String>(ResultModel.ERR_PARAM, "注销申请失败,参数有误", null);
		}
		if(!StringUtils.isEmpty(accountCancel.getReason()) && accountCancel.getReason().length() > Constant.LONG_DATA_LENGTH) {
			logger.warn("注销申请失败,申请理由输入过长:(");
			return new ResultModel<String>(ResultModel.WARN_DATA_LENGTH, "申请理由过长,请精简", null);
		}
		String uid = UserUtil.getUidByRequest(request);
		if(StringUtils.isEmpty(uid)) {
			logger.warn("注销申请失败,uid为空:(");
			return new ResultModel<String>(ResultModel.NOT_FOUND_OBJECT, "登录信息失效,请重新登录", null);
		}
		accountCancel.setUid(uid);
		return userService.cancelApplication(accountCancel);
	}
	
	/**
	 * 账号注销信息查询
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/queryCancelInfo",produces = "application/json;charset=UTF-8")
	@ResponseBody
	public ResultModel<?> queryCancelInfo(HttpServletRequest request) {
		String uid = UserUtil.getUidByRequest(request);
		if(StringUtils.isEmpty(uid)) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "参数出错", null);
		}
		return userService.queryCancelInfo(uid);
	}
	
	/**
	 * 获取当前用户的权限
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "getSelfResIds", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	@ResponseBody
	public ResultModel<?> getSelfResIds(HttpServletRequest request) {
		String uid = UserUtil.getUidByRequest(request);
		if(StringUtils.isEmpty(uid)) {
			logger.warn("根据uid获取当前用户权限失败,参数为空:(");
			return new ResultModel<String>(ResultModel.ERR_PARAM, "获取权限失败,参数为空", null);
		}
		return userService.getResIds(uid);
	}
	
	/**
	 * 绑定oa账号
	 * @param loginid
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "bindOaAccount", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public ResultModel<?> bindOaAccount(String loginid, HttpServletRequest request) {
		if(StringUtils.isEmpty(loginid)) {
			logger.warn("绑定失败,loginid为空:(");
			return new ResultModel<String>(ResultModel.ERR_PARAM, "绑定失败,参数有误", null);
		}
		return hrmResourceService.bindOaAccount(loginid, request);
	}
	
	/**
	 * 查询当前的用户是否已绑定过oa
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "queryHrmResourceBySelf", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	@ResponseBody
	public ResultModel<?> queryHrmResourceBySelf(HttpServletRequest request) {
		String uid = UserUtil.getUidByRequest(request);
		if(StringUtils.isEmpty(uid)) {
			logger.warn("绑定oa账号失败,登录信息失效:(");
			return new ResultModel<String>(ResultModel.ERR_PARAM, "登录失效,请刷新重新登录", null);
		}
		return hrmResourceService.queryHrmResourceByUid(uid);
	}

	/**
	 * 解绑oa账号
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "unBindOaAccount", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	@ResponseBody
	public ResultModel<?> unBindOaAccount(HttpServletRequest request) {
		String uid = UserUtil.getUidByRequest(request);
		if(StringUtils.isEmpty(uid)) {
			logger.warn("绑定oa账号失败,登录信息失效:(");
			return new ResultModel<String>(ResultModel.ERR_PARAM, "登录失效,请刷新重新登录", null);
		}
		return hrmResourceService.frontUnBindOaAccount(uid);
	}

	/**
	 * 解绑微信unionid
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "unBindWxUnionid", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	@ResponseBody
	public ResultModel<?> unBindWxUnionid(HttpServletRequest request) {
		String uid = UserUtil.getUidByRequest(request);
		if(StringUtils.isEmpty(uid)) {
			logger.warn("绑定oa账号失败,登录信息失效:(");
			return new ResultModel<String>(ResultModel.ERR_PARAM, "登录失效,请刷新重新登录", null);
		}
		return userService.frontUnBindWxUnionid(uid);
	}

	/**
	 * 二次登陆
	 * 
	 * @param phone
	 * @return 用户信息
	 */
	@RequestMapping(value = "aop/loginbymsg", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public ResultModel<?> aopLoginbymsg(HttpServletRequest request, @RequestBody LoginForm form) {
		logger.debug("通过短信二次登录");
		if(form == null || StringUtils.isEmpty(form.getCode())) {
			logger.warn("短信登录失败,请求参数为空:(");
			return new ResultModel<String>(ResultModel.ERR_PARAM, "请求参数有误", null);
		}
		Boolean flag = validateService.verifyPhoneCodeByType(form.getCode(), "phoneCodeOfAopLogin",request);
		 if(flag) {
			 request.getSession().setAttribute("aopLoginTime",new Date().getTime());
			 return new ResultModel<String>(ResultModel.SUCCESS, "登录成功", null); 
		 }else {
			 return new ResultModel<String>(ResultModel.ERR_PARAM, "验证码错误", null);
		 }
	}
	
	/**
	 * 	验证 用户昵称   是否存在  是否合法
	 * @param uname
	 * @return
	 */
	@RequestMapping(value = "verifyUname", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public ResultModel<?> verifyUname(String uname) {
		if(StringUtils.isEmpty(uname)||StringUtils.isEmpty(uname.trim())) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "昵称不能为空!",null);
		}
		boolean isExistUname = userService.isExistUname(uname,null);
		if(isExistUname) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "昵称已存在!",String.valueOf(isExistUname));
		}
		return new ResultModel<String>(ResultModel.SUCCESS, "成功", String.valueOf(isExistUname));
	}
	
	/**
	 *   未登录 点赞功能
	 *    目前是去远方功能 
	 *    后期可能会更改其他类型
	 * @param code
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "loginStarClick", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	@ResponseBody
	public ResultModel<?> loginStarClick(String code, Integer type, HttpServletRequest request) {
		if (StringUtils.isEmpty(code) || code.length() != 32) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, ResultModel.ERR_PARAM_MSG, null);
		}
		String addr = request.getRemoteAddr();
		loginPageFilesService.addLoginStarLog(addr,code);
		return new ResultModel<String>(ResultModel.SUCCESS, ResultModel.SUCCESS_MSG, null);
	}
	
	/**
	 * 获取登录页面信息（背景图）
	 * @param request
	 * @return
	 */
	@RequestMapping(value="getLoginPageInfo",produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	@ResponseBody
	public  ResultModel<?> getLoginPageInfo(HttpServletRequest request) {
		LoginPageFilesEntity entity = loginPageFilesService.getLoginPageInfo();
		String baseUrl = "/account/file/viewimg?fileName=%s&type=2";
		if(entity !=null) {
			if(!StringUtils.isEmpty(entity.getBgFile())) {
				entity.setBgFile(String.format(baseUrl, entity.getBgFile()));
			}
			if(!StringUtils.isEmpty(entity.getQrFile())) {
				entity.setQrFile(String.format(baseUrl, entity.getQrFile()));
			}
			if(!StringUtils.isEmpty(entity.getTitleFile())) {
				entity.setTitleFile(String.format(baseUrl, entity.getTitleFile()));
			}
			int count = loginPageFilesService.getCountByLpfId(entity.getLpfId());
			entity.setCount(count);
		}
		return new ResultModel<LoginPageFilesEntity>(ResultModel.SUCCESS, ResultModel.SUCCESS_MSG, entity);
	}
	
	/**
	 * 查询用户积分数
	 * @param uid
	 * @return
	 */
	@RequestMapping(value = "integral/{uid}", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Object getUserInteger(String jsonpCallback,@PathVariable("uid") String uid) {
		int integral = 0;
		if(!StringUtils.isEmpty(uid)) {
			UserEntity user = userService.queryUserByUid(uid);
			if(user.getIntegral() != null) {
				integral = user.getIntegral();
			}
		}
		if(!StringUtils.isEmpty(jsonpCallback)){
			JSONPObject jo = new JSONPObject(jsonpCallback);
			jo.addParameter(integral);
			return jo;
		} else{
			return integral;
		}
	}
}